import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  CheckOutlined,
  SearchOutlined,
  UndoOutlined
} from '@ant-design/icons';
import {
  Button,
  message,
  Form,
  DatePicker,
  Upload,
  UploadProps,
  Row,
  Col,
  Input,
  Popconfirm,
  Select,
  Checkbox,
} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import '@/assets/css/index.less';
import {
  deletePhotoById,
  getPhotoCategoryList,
  getPhotoFile,
  getPhotoList,
} from '@/services/pictureManager';
import { history } from 'umi';
import formatDate from '@/utils/formatDate';
import {
  delHomepageVersion,
  getHomepageVersionList,
  restoreWithVersion,
} from '@/services/dataRestoreManager';

const DataRestore: React.FC = () => {
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(40);
  const [dataArray, setDataArray] = useState([]);
  const [pageSize, setPageSize] = useState(10);
  const [pagination, setPagination] = useState({
    current: page,
    pageSize: pageSize,
    position: ['bottomRight'],
    size: 'small',
    showSizeChanger: true,
    total: total,
  });

  const handleDelete = async (record: any) => {
    try {
      const res = await delHomepageVersion({ id: record.id });
      console.log(res);
      if(res.code == '0'){
        message.success('删除成功');
      }
    } catch (error) {
      message.error('删除失败');
    }
    queryData();
  };

  const handleRestore = async (record) => {
    let actIndex = dataArray.findIndex((item) => item.act == 1);
    let IdObject = {};
    if (actIndex == -1) {
      IdObject = {
        newId: record.id,
      };
    } else {
      IdObject = {
        newId: record.id,
        oldId: dataArray[actIndex].id,
      };
    }

    const res = await restoreWithVersion(IdObject);
    if (res.code == '0') {
      queryData();
      message.success('还原点设置成功！');
    } else {
      message.error('还原点设置失败！');
    }
  };
  const handleTableChange = (pagination: any) => {
    setPage(pagination.current);
    setPageSize(pagination.pageSize);
    setPagination({ ...pagination });
  };

  useEffect(() => {
    queryData();
  }, [page, pageSize]);
  useEffect(()=>{
    queryData();
  },[])

  const queryData = async () => {
    let values = form.getFieldsValue();
    const msg = await getHomepageVersionList(values);
    setDataArray(msg.data);
    setPagination({ ...pagination, total: msg.data.total });
  };
  const columns: ProColumns[] = [
    {
      title: '当前节点',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'firstSrc',
      render: (_, record) => [record.act == 1 ? <CheckOutlined /> : ''],
    },
    {
      title: '节点名称',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'description',
    },
    {
      title: '还原点',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'createdTime',
    },
    {
      title: '创始人',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'createdBy',
    },
    {
      title: '操作',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'id',
      render: (_, record) => [
        <Popconfirm title="确定是否删除?" onConfirm={() => handleDelete(record)} key="delete">
          <a style={{ color: 'red' }}>
            <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined />}>
              删除
            </Button>
          </a>
        </Popconfirm>,
        <a
          key="edit"
          onClick={() => {
            handleRestore(record);
          }}
        >
          <Button className={'buttonMargin'} type={'primary'} shape={'round'} icon={<EditOutlined />}>
            点击还原
          </Button>
        </a>,
      ],
    },
  ];

  const _initSearchForm = () => {
    return (
      <div className="ant-pro-table-search ant-pro-table-search-query-filter">
        <Form
          form={form}
          className="ant-form ant-form-horizontal ant-pro-form-query-filter"
          layout="inline"
        >
          <Row style={{ width: '100%' }}>
            <Col span={4}>
              <Form.Item label="节点名称" name="description">
                <Input
                  placeholder="请输入节点名称"
                  onChange={() => {
                    queryData();
                  }}
                />
              </Form.Item>
            </Col>
            <Col span={10}>

            </Col>
            <Col
              span={6}
              offset={2}
              className="basic-search-form-submit-btn"
              style={{ display: 'flex', justifyContent: 'flex-end' }}
            >
              <Button
                onClick={() => {
                  form.resetFields();
                  queryData();
                }}
              >                <UndoOutlined />

                重置
              </Button>
              &nbsp;&nbsp;
              <Button type="primary" htmlType="submit" onClick={() => queryData()}>
                <SearchOutlined />
                查询
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };
  return (
    <PageContainer>
      {      _initSearchForm()}
      <ProTable
        search={false}
        // headerTitle="视媒管理"
        actionRef={actionRef}
        rowKey="id"
        tableStyle={{ textAlign: 'center' }}
        options={false}
        pagination={pagination}
        dataSource={dataArray}
        onChange={handleTableChange}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              // location.href = '/picturePublish'
              location.href = '#/webDesign/index';
            }}
          >
            <PlusOutlined />
            创建
          </Button>,
        ]}
        // request={async () => {

        // const msg = await getHomepageVersionList();

        // return {
        //     data: msg.data ,
        //     // success 请返回 true，
        //     // 不然 table 会停止解析数据，即使有数据
        //     success: msg.message==='success',
        //     // 不传会使用 data 的长度，如果是分页一定要传
        //     // total: number,
        // };
        // }}
        columns={columns}
        // rowSelection={{
        // onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        // },
        // }}
      ></ProTable>
    </PageContainer>
  );
};
const Index: React.FC = () =>{
  return(
    <div>123</div>
  )
}
export default DataRestore;
